﻿///***************************************************************
/// 시  스  템 : Updms.Mny
/// 단위시스템 : MNY
/// 계      층 : Presentation Layer
/// 프로그램명 : Mny2021r
/// 파  일  명 : Mny2021r.aspx.cs
/// 설      명 : 기간별출납내역
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2011-09-01 송시명   최초 작성
///***************************************************************
using System;
using System.Collections;
using System.Data;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.WebControls;

using SMFramework.Data;
using SMFramework.Utility;
using SMFramework.Web.UI.WebControls.SMGridView;

using Base.AppFramework.Web.UI.CommandBar;
using Base.Dac;

using Updms.Common.BaseClass;
using Updms.Mny.Exe;


namespace Updms.Mny
{
	public partial class Mny2021r : Updms.Common.BaseClass.PageBase
	{
		#region 전역영역

		//프로그램상수
		public static readonly string PID = "Mny2021r";
		public static readonly string gs_path_info = "/updms/Mny/" + PID + ".aspx";

		Global global = new Global();

		//검색
		protected string kw1 = "";	//조회시작년월
		protected string kw2 = "";	//조회종료년월

		//메뉴 선택값
		protected string gs_sm = "";

		#endregion

		#region Page_Load, OnPageLoad

		protected void Page_Load(object sender, EventArgs e)
		{
			SetInit();
			if (!Page.IsPostBack)
			{
				// 최초 화면 로딩시 처리해야 할 부분
				OnPageLoad();
				SearchProcess();
			}
			else
			{
				CallJavaScriptMethodInAjax("setResize();");
			}
		}

		// OnPageLoad
		private void OnPageLoad()
		{
			SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
			SetYearMonth();
			SetSearchParameter();
		}

		#endregion

		#region InitializeComponent

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);
		}

		#endregion	

		#region SetInit, SetSearchParameter

		//초기값설정
		private void SetInit()
		{
			lbl_search_flag.Text = "INIT";
			
			gs_sm = (Request.QueryString["sm"] == null || Request.QueryString["sm"].Trim().Length != 7)
					? global.GetDirDepth(PID) : Request.QueryString["sm"].ToString();
		}

		//검색파라미터
		private void SetSearchParameter()
		{
			kw1 = ddl_search_from_year.SelectedValue + "-" + ddl_search_from_month.SelectedValue;
			kw2 = ddl_search_to_year.SelectedValue + "-" + ddl_search_to_month.SelectedValue;

			//기준년월을 히든으로 저장해둠
			lbl_month_list.Text = DateUtil.GetDiffMonthList(kw1, kw2);
		}

		#endregion

		#region 마스터 Method (SetYearMonth)

		// 검색조건의 년월설정
		private void SetYearMonth()
		{
			ddl_search_from_year.Items.Clear();
			ddl_search_to_year.Items.Clear();

			//현재년도 기준으로 ±2년 -> SEARCH_Y_MIN년부터 현재+1년
			int li_f_year = Convert.ToInt32(SEARCH_Y_MIN);
			int li_t_year = Convert.ToInt32(DateUtil.GetYearEx(1, "yyyy"));
			for (int i = li_f_year; i <= li_t_year; i++)
			{
				string ls_year = i.ToString();
				ddl_search_from_year.Items.Add(new ListItem(ls_year, ls_year));
				ddl_search_to_year.Items.Add(new ListItem(ls_year, ls_year));
			}

			SetYearMonth(-12);
		}

		// 검색조건의 년월설정 - 기간지정
		private void SetYearMonth(int li_term)
		{
			ddl_search_from_year.SelectedValue = DateUtil.GetMonthEx(li_term, "yyyy"); //x개월전년도
			ddl_search_from_month.SelectedValue = DateUtil.GetMonthEx(li_term, "MM"); //x개월전월
			ddl_search_to_year.SelectedValue = DateUtil.GetYearEx(0, "yyyy"); // 현재년도
			ddl_search_to_month.SelectedValue = DateUtil.GetMonthEx(0, "MM"); // 현재월
		}

		#endregion

		#region 디테일 Method (SetChartByAccount)

		//계정별 라인챠트
		private void SetChartByAccount(GridView gv, int row_idx)
		{
			//시리즈
			chart_line.Data.Series = 1;
			string series = String.Empty;

			series = ConversionUtil.ExtractStrBtwnChar(gv.Rows[row_idx].Cells[4].Text, ";\">", "</a>");

			chart_line.Series[0].Text = series;

			//초기화
			chart_line.Data.Clear();

			string monthList = DateUtil.GetDiffMonthList(kw1, kw2);
			string[] monthLists = monthList.Split(',');

			double ld_avg = 0.0; //평균
			int li_sum = 0; //합계
			int li_cnt = 0; //금액이 0이상인 월의 수

			for (int i = 0; i < monthLists.Length; i++)
			{
				int value = Convert.ToInt32(ConversionUtil.RemoveComma(ConversionUtil.ExtractStrBtwnChar(gv.Rows[row_idx].Cells[i + 5].Text, ");\">", "</span>")));

				//수동으로 데이터 바인딩
				chart_line.Data[0, i] = value;
				li_sum = li_sum + value;

				//X축 라벨링
				chart_line.AxisX.Labels[i] = monthLists[i].ToString();

				//0이상일때만 보여준다.
				if (chart_line.Data[0, i] > 0)
				{
					chart_line.Points[0, i].PointLabels.Visible = true;
					li_cnt++;
				}
				else
				{
					chart_line.Points[0, i].PointLabels.Visible = false;
				}
			}

			if (li_cnt > 0)
			{
				ld_avg = li_sum / li_cnt;
			}

			//CustomGridLine 초기화
			chart_line.AxisY.CustomGridLines.Clear();

			//CustomGridLine
			ChartFX.WebForms.CustomGridLine cgl1 = new ChartFX.WebForms.CustomGridLine();
			cgl1.Value = ld_avg;
			cgl1.Color = System.Drawing.Color.Red;
			cgl1.Width = 2;
			cgl1.Text = "Avg. : " + ld_avg.ToString("#,###.##");
			cgl1.Alignment = StringAlignment.Far;
			cgl1.LineAlignment = StringAlignment.Near;
			cgl1.TextColor = Color.Black;

			chart_line.AxisY.CustomGridLines.Add(cgl1);

			mpe_chart_line.Show();
		}

		#endregion

		#region CRUD (SelectProcess, SearchProcess)

		//조회
		private void SelectProcess()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			//검색
			lo_dp.AddProperty("ls_dt_from", typeof(string), kw1);
			lo_dp.AddProperty("ls_dt_to", typeof(string), kw2);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);
			lo_dp.AddProperty("ls_is_excel", typeof(string), "false");

			using (Mny2021r_NT _Mny2021r_NT = new Mny2021r_NT())
			{
				lo_ds.Merge(_Mny2021r_NT.GetRegionalInOutAnalysisList(lo_dp));
			}

			gv_data_nodata.Visible = !DataSetUtil.CheckRowCount(lo_ds, "UPDMS_MNY_REPORT");

			gv_account.DataSource = lo_ds;
			gv_data.DataSource = lo_ds;
			gv_total.DataSource = lo_ds;
			
			gv_account.DataBind();
			gv_data.DataBind();
			gv_total.DataBind();
		}		

		//검색
		private void SearchProcess()
		{
			lbl_search_flag.Text = "SEARCH";
			SetSearchParameter();
			SelectProcess();
		}

		#endregion		

		#region Page_PreRender, ChangePageMode

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				using (AccessCheck access = new AccessCheck())
				{
					//접근권한 체크
					if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
					{
						Response.Redirect(URL_NO_AUTHORITY_REDIRECT_BASE);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
					}
					//사용권한별 버튼처리
					PagePreRender.SetVisibleCtrl(this, access.CheckPgmUsingGrant(USER_DIV, PID), access.GetVisibleCtrl(PID));
				}
			}
			ChangePageMode();
		}

		// ChangePageMode
		private void ChangePageMode()
		{
			string width = (LANG_SET.ToUpper() == "KO") ? "210" : "320";
			div_account.Attributes.Add("style", "width:" + width + "px");
		}

		#endregion

		#region GridView이벤트

		//구분,계정
		protected void gv_account_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			GridView gv = (GridView)sender;

			if (e.Row.RowType == DataControlRowType.Header)
			{
				e.Row.Cells[0].Text = GetXmlMsg("MNY_001");	//구분
				e.Row.Cells[1].Text = GetXmlMsg("CRD_002");	//계정
			}

			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				e.Row.Cells[1].Text
					= "<a href=\"#\" onclick=\"viewChartByAccount('" + e.Row.RowIndex.ToString() + "');\">" + e.Row.Cells[1].Text + "</a>";

				switch (gv.DataKeys[e.Row.RowIndex].Values["View_Order"].ToString())
				{
					case "AA001T": //수입합계
						e.Row.Attributes.Add("class", "sub_total_v1");
						break;
					case "AA002T": //지출합계
						e.Row.Attributes.Add("class", "sub_total_v1");
						break;
					case "AA003T": //저축합계
						e.Row.Attributes.Add("class", "sub_total_v1");
						break;
					case "AA004T": //수입-저축-지출
						e.Row.Attributes.Add("class", "total_v3");
						for (int i = 0; i < e.Row.Cells.Count; i++)
						{
							e.Row.Cells[i].Attributes.Add("class", "div_line_tb_dbl");
						}
						break;
					default:
						break;
				}
			}
			//머지
			SMGridView sGv = new SMGridView();
			sGv.RowSpanGridView(gv_account, 0);//2.Class_Nm
		}

		//데이터
		protected void gv_data_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			GridView gv = (GridView)sender;

			e.Row.Cells[0].Visible = false; //View_Order 숨김
			e.Row.Cells[1].Visible = false; //Class 숨김
			e.Row.Cells[2].Visible = false; //Class_Nm 숨김
			e.Row.Cells[3].Visible = false; //Account 숨김
			e.Row.Cells[4].Visible = false; //Account_Nm 숨김
			e.Row.Cells[e.Row.Cells.Count - 1].Visible = false; //Total_Amt 숨김

			if (e.Row.RowType == DataControlRowType.Header)
			{
				e.Row.HorizontalAlign = HorizontalAlign.Center;
			}

			//View_Order,Class,Class_Nm,Account,Account_Nm,...,Total_Amt
			string[] baseYm = (",,,,," + lbl_month_list.Text + ",").Split(',');

			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//금액컬럼 정렬 및 HtmlDecode
				for (int i = 5; i < e.Row.Cells.Count - 1; i++)
				{
					//금액에 링크걸기
					string account = gv.DataKeys[e.Row.RowIndex].Values["Account"].ToString();
					bool isTotal = gv.DataKeys[e.Row.RowIndex].Values["View_Order"].ToString().EndsWith("T");
					string base_ym = baseYm[i];
					string data = e.Row.Cells[i].Text;
					string link = (data == "0" || isTotal) ? "javascript:void(0);" : "javascript:viewDetailList('" + account + "','" + base_ym + "');";
string finalData = "<span onclick=\"" + link + "\">" + data + "</span>";

					e.Row.Cells[i].Text = finalData;
					e.Row.Cells[i].HorizontalAlign = HorizontalAlign.Right;
				}

				switch (gv.DataKeys[e.Row.RowIndex].Values["View_Order"].ToString())
				{
					case "AA001T": //수입합계
						e.Row.Attributes.Add("class", "sub_total_v1");
						break;
					case "AA002T": //지출합계
						e.Row.Attributes.Add("class", "sub_total_v1");
						break;
					case "AA003T": //저축합계
						e.Row.Attributes.Add("class", "sub_total_v1");
						break;
					case "AA004T": //수입-저축-지출
						e.Row.Attributes.Add("class", "total_v3");
						for (int i = 0; i < e.Row.Cells.Count; i++)
						{
							e.Row.Cells[i].Attributes.Add("class", "div_line_tb_dbl");
						}
						break;
					default:
						break;
				}
			}
		}

		protected void gv_total_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			GridView gv = (GridView)sender;

			if (e.Row.RowType == DataControlRowType.Header)
			{
				e.Row.Cells[0].Text = GetXmlMsg("MNY_002");	//총액
			}

			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//e.Row.Cells[1].Text
				//	= "<a href=\"#\" onclick=\"viewChartByAccount('" + e.Row.RowIndex.ToString() + "');\">" + e.Row.Cells[1].Text + "</a>";

				switch (gv.DataKeys[e.Row.RowIndex].Values["View_Order"].ToString())
				{
					case "AA001T": //수입합계
						e.Row.Attributes.Add("class", "sub_total_v1");
						break;
					case "AA002T": //지출합계
						e.Row.Attributes.Add("class", "sub_total_v1");
						break;
					case "AA003T": //저축합계
						e.Row.Attributes.Add("class", "sub_total_v1");
						break;
					case "AA004T": //수입-저축-지출
						e.Row.Attributes.Add("class", "total_v3");
						for (int i = 0; i < e.Row.Cells.Count; i++)
						{
							e.Row.Cells[i].Attributes.Add("class", "div_line_tb_dbl");
						}
						break;
					default:
						break;
				}
			}
		}

		#endregion

		#region 버튼이벤트

		//6개월
		protected void sbtn_6_m_Click(object sender, EventArgs e)
		{
			SetYearMonth(-5);
			SearchProcess();
		}

		//12개월
		protected void sbtn_12_m_Click(object sender, EventArgs e)
		{
			SetYearMonth(-12);
			SearchProcess();
		}

		//전체
		protected void sbtn_all_m_Click(object sender, EventArgs e)
		{
			ddl_search_from_year.SelectedIndex = 0;
			ddl_search_from_month.SelectedIndex = 0;
			ddl_search_to_year.SelectedIndex = ddl_search_to_year.Items.Count - 1;
			ddl_search_to_month.SelectedIndex = ddl_search_to_month.Items.Count - 1;

			SearchProcess();
		}

		//검색
		protected void ibtn_search_Click(object sender, EventArgs e)
		{
			SearchProcess();
		}		

		//엑셀
		protected void ibtn_excel_Click(object sender, EventArgs e)
		{
			SetSearchParameter();

			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			//검색
			lo_dp.AddProperty("ls_dt_from", typeof(string), kw1);
			lo_dp.AddProperty("ls_dt_to", typeof(string), kw2);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);
			lo_dp.AddProperty("ls_is_excel", typeof(string), "true");

			using (Mny2021r_NT _Mny2021r_NT = new Mny2021r_NT())
			{
				lo_ds.Merge(_Mny2021r_NT.GetRegionalInOutAnalysisList(lo_dp));
			}

			//컬럼수만큼의 크기를 갖는 배열을 생성
			string[] columns = DateUtil.GetDiffMonthList(kw1, kw2).Split(',');
			string[] headerTexts = new string[columns.Length + 3]; // +3(Class_Nm, Account_Nm, Total_Amt)

			headerTexts[0] = "Class_Nm^" + global.GetLabelNmBySeq(81, LANG_SET); //구분
			headerTexts[1] = "Account_Nm^" + global.GetLabelNmBySeq(55, LANG_SET); //계정

			for (int i = 2; i < headerTexts.Length - 1; i++)
			{
				headerTexts[i] = columns[i - 2] + "^" + columns[i - 2];
			}

			headerTexts[headerTexts.Length - 1] = "Total_Amt^" + global.GetLabelNmBySeq(560, LANG_SET); //합계

			string fileName = PID + "(" + global.GetMenuTitle(PID, LANG_SET) + ")";
			ExcelUtil.CreateExcelFileX(this.Page, fileName, lo_ds, headerTexts);
		}
		
		//챠트 생성
		protected void lbtn_set_chart_Click(object sender, EventArgs e)
		{
			SetSearchParameter();
			SetChartByAccount(gv_data, Convert.ToInt32(h_row_idx.Value));
		}

		#endregion

	}
}
